package database

import (
	"blog/config"
	"context"
	"github.com/redis/go-redis/v9"
	"sync"
	"time"
)

var (
	redisOnce   sync.Once
	redisClient *redis.Client
)

// GetRedisClient 单例模式
func GetRedisClient() *redis.Client {
	redisOnce.Do(func() {
		cfg := config.GetConfig()
		client, _ := NewRedis(&cfg.Redis)
		redisClient = client
	})
	return redisClient
}

func NewRedis(cfg *config.Redis) (*redis.Client, error) {

	client := redis.NewClient(&redis.Options{
		Addr:         cfg.Address,
		Password:     cfg.Password,
		DB:           cfg.DB,
		PoolSize:     cfg.PoolSize,
		DialTimeout:  5 * time.Second,
		ReadTimeout:  3 * time.Second,
		WriteTimeout: 3 * time.Second,
		PoolTimeout:  4 * time.Second,
	})
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	if err := client.Ping(ctx).Err(); err != nil {
		return nil, err
	}
	return client, nil
}
